/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';
var videoSelect=[];
var audioSelect=[];
var videoElement='';
var callback='';
function gotDevices(deviceInfos) {
  videoSelect=[],audioSelect=[];
  for (var i = 0; i !== deviceInfos.length; ++i) {
    var deviceInfo = deviceInfos[i];
    if (deviceInfo.kind === 'audioinput') {
      audioSelect.push(deviceInfo.deviceId);
    } else if (deviceInfo.kind === 'videoinput') {
      console.log("deviceId=" , deviceInfo);
      if(deviceInfo.label.indexOf('Dummy')!=-1){
        videoSelect.push(deviceInfo.deviceId);
      }
    } else {
      console.log('Found one other kind of source/device: ', deviceInfo);
    }
    // var option = document.createElement('option');
    // option.value = deviceInfo.deviceId;
    // if (deviceInfo.kind === 'audioinput') {
    //   option.text = deviceInfo.label ||
    //     'microphone ' + (audioSelect.length + 1);
    //   audioSelect.appendChild(option);
    // } else if (deviceInfo.kind === 'videoinput') {
    //   option.text = deviceInfo.label || 'camera ' +
    //     (videoSelect.length + 1);
    //   videoSelect.appendChild(option);
    // } else {
    //   console.log('Found one other kind of source/device: ', deviceInfo);
    // }
  }
}

function getStream() {
  if (window.stream) {
    window.stream.getTracks().forEach(function(track) {
      track.stop();
    });
  }
  var video = videoSelect?videoSelect[0]:'';
  var audio = audioSelect?audioSelect[0]:'';
  console.log("videoSelect:"+video+",audioSelect:"+audio);
  var constraints = {
    audio: {
      deviceId: {exact: audio}
    },
    video: {
      deviceId: {exact: video}
    }
  };
  navigator.mediaDevices.getUserMedia(constraints).
    then(gotStream).catch(handleError);
}

function gotStream(stream) {
  window.stream = stream; // make stream available to console
  videoElement.srcObject = stream;
  callback();
}

function handleError(error) {
  console.log('Error: ', error);
}

export function playVideo(video,c){
  console.log("navigator.mediaDevices",navigator.mediaDevices);
  videoElement=video
  callback=c;
  navigator.mediaDevices.enumerateDevices()
    .then(gotDevices).then(getStream).catch(handleError);
}


